package cn.wolfcode.trip.app.web.controller;

import cn.wolfcode.trip.app.util.FreemarkUtil;
import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author by mycp
 * @Classname RegionsController
 * @Description TODO
 * @Date 2018/11/4 19:47
 */
@RestController
@RequestMapping("/regions")
public class RegionsController {
    @Autowired
    private IRegionService regionService;

    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private ServletContext ctx;

    /**
     * 获取所有的区域
     * 参数: state=xx
     * @return
     */
    @GetMapping
    @ResponseBody
    public Object list(Integer state){
        List<Region> list = regionService.list(state);
        return list;
    }

    /**
     * 接口: /regions/{id}/strategies
     * 获取某个区域的推荐攻略
     */
    @GetMapping(value = "/{regionId}/strategies", produces = "text/html;charset=utf-8")
    public void queryStrategies(StrategyQueryObject qo, HttpServletResponse resp) throws Exception {
        Map<String, Object> map = new HashMap<>();

        // 获取写入资源的真实路径
        String dir = ctx.getRealPath("/template");

        // 推荐攻略分为两种情况
        // 全部攻略: 需要分页
        qo.setState(-1L);
        // 每页查询两条数据
        qo.setPageSize(2);
        PageInfo pageInfo = strategyService.queryEnable(qo);

        // 如果是分页操作, 则只需要查询全部攻略, 不需要再查询推荐攻略
        if (qo.getCurrentPage() != 1){
            map.put("info", pageInfo);
            FreemarkUtil.writeDate(dir, "classify.ftl", map, resp.getWriter());
            return;
        }

        // 精品推荐攻略 状态: 2 推荐, 不仅行分页处理
        qo.setState(2L);
        qo.setPageSize(0);
        List<Strategy> commends = strategyService.query(qo).getList();

        // 存储数据
        map.put("commends", commends);
        map.put("info", pageInfo);
        // 存储对应的区域id
        map.put("id", qo.getRegionId());




        // 生成模板
        FreemarkUtil.writeDate(dir, "strategyContent.ftl", map, resp.getWriter());
    }

    /**
     * 接口:保存标签
     * 资源:/regions/{id}/tags
     * 动作:POST
     * 参数: state=xx
     * @return
     */
    @PostMapping("/{regionId}/tags")
    public Object saveTags(String[] tags){
        List<Region> list = regionService.list(1);
        return null;
    }
}
